﻿Option Explicit On

Public Class Form1
    Public path As String = Application.StartupPath
    Public state As String
    Public timeGlobal As Long
    Public timePause As Long
    Public timeEsercizio As Long
    Public nSerie As Integer
    Public totEsercizi As Integer
    Public totSeries As Integer
    Public totPausa As Long
    Public totPausaBig As Long
    Public currentEsercizio As Integer
    Public currentGiorno As String
    Public currentAllenamento As Integer = 1
    Public idis(100) As Integer
    Public cursorVisible As Boolean = True
    Public searchMnuIds(10) As Integer
    Public searchMnuIds_count As Integer

    Private Sub Form1_HandleDestroyed(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles Me.HandleDestroyed
        cn.Close()
        writeConfig(path & "/config.ini")
        'playSound("sound exit")
        deinitSound()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'pausaSingle("5''")
        'End
        loadPreferenze()
        initSound()
        connetti(getConfig("dbfile"))
        loadGruppi()
        ingrigisciGiorniVuoti()
        loadAllenamento(Date.Today.ToString("ddd"))
        setState("new")
        totPausaBig = pausaLong(getConfig("pausa lunga"))

        gbEdit.Visible = False
        gbEdit.Location = gbEs.Location
    End Sub

    Sub loadAllenamento(ByVal giorno As String)
        ingrigisciGiorniVuoti()

        ' carica gli esercizi dell'allenamento
        query("SELECT * FROM qallenamento WHERE giorno='" + giorno + "' AND allenamento.id=" & _
              currentAllenamento & " ORDER BY ordine")
        ' inserisci i nomi dell'allenamento della lista
        totEsercizi = 0
        lstAllenamenti.Items.Clear()
        currentGiorno = giorno

        resetDays()
        Select Case giorno
            Case "lun" : lblGiornoLun.BackColor = Color.AliceBlue
            Case "mar" : lblGiornoMar.BackColor = Color.AliceBlue
            Case "mer" : lblGiornoMer.BackColor = Color.AliceBlue
            Case "gio" : lblGiornoGio.BackColor = Color.AliceBlue
            Case "ven" : lblGiornoVen.BackColor = Color.AliceBlue
            Case "sab" : lblGiornoSab.BackColor = Color.AliceBlue
            Case "dom" : lblGiornoDom.BackColor = Color.AliceBlue
        End Select

        If rs.RecordCount = 0 Then
            'MsgBox("Non sono presenti allenamenti per il giorno " & giorno)
            cmdAction.Enabled = False
            opzCapture(False)
            gbEs.Enabled = False
            azzeraEsercizio()
            Exit Sub
        Else
            cmdAction.Enabled = True
            gbEs.Enabled = True
        End If

        Dim indice As Integer
        While (Not rs.EOF)
            indice = lstAllenamenti.Items.Add(rs.Fields.Item("esercizi.nome").Value)
            idis(indice) = rs.Fields.Item("esercizi.id").Value
            rs.MoveNext()
            totEsercizi += 1
        End While
        ' seleziona primo esercizio
        changeEsercizio(0)
    End Sub

    Sub resetDays()
        For Each o As Control In Me.Controls
            If o.Name.Contains("lblGiorno") Then
                o.BackColor = Me.BackColor
            End If
        Next
    End Sub

    Sub selectEsercizio(ByVal index As Integer)
        query("SELECT * FROM qallenamento WHERE giorno='" + currentGiorno + "' AND allenamento.id=" & _
              currentAllenamento & " ORDER BY ordine")

        rs.MoveFirst()
        rs.Move(index)
        lblNome.Text = capitalizza(field("esercizi.nome"))
        lblRipetizioni.Text = "Ripetizioni: " + field("serie") + " x " + field("spinte")
        lblPausa.Text = "Pausa: " + convPausa(field("pausa"))
        If (field("carico") <> "") Then
            lblCarico.Text = "Carico: " + field("carico") + " kg"
        Else
            lblCarico.Text = "Carico: --"
        End If
        lblFascia.Text = "Fascia muscolare: " + field("fasce.nome")
        totSeries = field("serie")
        totPausa = pausaLong(field("pausa"))
        'totPausa = pausaLong(0.1)
        nSerie = 0
        currentEsercizio = index
        'lblNote.Text = "Note: "+field("esercizi.nome")
    End Sub

    Sub azzeraEsercizio()
        lblNome.Text = "Giorno di riposo"
        lblRipetizioni.Text = "Ripetizioni: --"
        lblPausa.Text = "Pausa: --"
        lblCarico.Text = "Carico: --"
        lblFascia.Text = "Fascia muscolare: --"
    End Sub

    Sub changeEsercizio(ByVal num As Integer)
        selectEsercizio(num)
        lstAllenamenti.SelectedIndex = num
        'lblTimerE.Text = "0:00:00"
        'lblTimerP.Text = "0:00"
        timeEsercizio = 0
    End Sub

    Sub setState(ByVal s As String)
        Select Case s
            Case "new"
                cmdAction.Text = "Comincia allenamento"
                lblTimerE.Text = "0:00:00"
                lblTimerA.Text = "0:00:00"
                lblTimerP.Text = "0:00"
                timeEsercizio = 0
                timeGlobal = 0
                timePause = 0
            Case "editing"
                gbEdit.Visible = True
                gbEs.Visible = False
                txtCarico.Text = lblCarico.Text.Substring(8)
                txtNome.Text = lblNome.Text
                txtPausa.Text = lblPausa.Text.Substring(7)
                txtRipetizioni.Text = lblRipetizioni.Text.Substring(13)
                lstAllenamenti.Enabled = False
                cmdAction.Enabled = True
                cmdAction.Text = "Editing - clicca per confermare"
                enableGiorno(False)
            Case "work"
                nSerie += 1
                cmdAction.Text = "Serie " & (nSerie) & "/" & totSeries & " - clicca quando finito"
                t.Start()
            Case "next"
                playSound("sound ultima serie")
                nSerie += 1
                cmdAction.Text = "Serie " & (nSerie) & "/" & totSeries & " - clicca per passare al prossimo esercizio"
                t.Start()
            Case "last"
                nSerie += 1
                cmdAction.Text = "Serie " & (nSerie) & "/" & totSeries & " - ultimo esercizio"
                t.Start()
            Case "pause"
                lblPausaTimer.Text = "Pausa serie " & (nSerie) & "/" & totSeries
                timePause = totPausa
                cmdAction.Text = "Attendere la pausa"
            Case "pauseBig"
                lblPausaTimer.Text = "Pausa esercizio " & lblNome.Text
                changeEsercizio(currentEsercizio + 1)
                timePause = totPausaBig
                cmdAction.Text = "Prepararsi per il prossimo esercizio"
            Case "end"
                timePause = totPausaBig
                cmdAction.Text = "Fine dell'allenamento - Esci"
                lstAllenamenti.Enabled = True
                enableGiorno(True)
                t.Stop()
        End Select
        state = s
    End Sub

    Private Sub cmdAction_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAction.Click
        playSound("sound button")
        Select Case state
            Case "new" 'parti con il primo esercizio
                lstAllenamenti.SelectedIndex = 0
                changeEsercizio(0)
                lstAllenamenti.Enabled = False
                enableGiorno(False)
                setState("work")
            Case "work"
                If (nSerie < totSeries) Then
                    setState("pause")
                End If
            Case "next"
                setState("pauseBig")
            Case "last"
                setState("end")
            Case "end"
                End
            Case "editing"
                Dim pausa As Single = pausaSingle(txtPausa.Text)
                Dim carico As String = caricoVal(txtCarico.Text)
                Dim rip As Integer
                Dim ser As Integer
                Dim riperet As Integer = ripetizioni(txtRipetizioni.Text, ser, rip)
                If pausa > 0 And riperet > 0 Then
                    Dim sel As Integer = lstAllenamenti.SelectedIndex
                    query("UPDATE allenamento SET carico=" & carico & ", serie=" & ser & _
                          ", spinte=" & rip & ", pausa='" & pausa & "' WHERE id=" & currentAllenamento & _
                          " AND giorno='" & currentGiorno & "' AND ordine=" & sel)
                    loadAllenamento(currentGiorno)
                    lstAllenamenti.SelectedIndex = sel
                    changeEsercizio(sel)
                    gbEdit.Visible = False
                    gbEs.Visible = True
                    enableGiorno(True)
                    lstAllenamenti.Enabled = True
                    setState("new")
                Else
                    playSound("sound abort")
                    MsgBox("Valori non validi")
                End If
        End Select
    End Sub

    Private Sub t_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles t.Tick
        timeGlobal += 1
        Select Case state
            Case "pause"
                timePause -= 1
                lblTimerP.Text = toTime(timePause, False)
                timeEsercizio += 1
                lblTimerE.Text = toTime(timeEsercizio)
                If timePause = 0 Then
                    lblPausaTimer.Text = "Pausa"
                    playSound("sound pausa")
                    If nSerie < totSeries - 1 Then
                        setState("work")
                    ElseIf currentEsercizio = totEsercizi - 1 Then
                        setState("last")
                    Else
                        setState("next")
                    End If
                ElseIf timePause < 10 Then
                    playSound("sound beep")
                End If
            Case "pauseBig"
                timePause -= 1
                lblTimerP.Text = toTime(timePause, False)
                'timeEsercizio += 1
                'lblTimerE.Text = toTime(timeEsercizio)
                If timePause = 0 Then
                    playSound("sound pausa")
                    setState("work")
                ElseIf timePause < 10 Then
                    playSound("sound beep")
                End If
            Case "work"
                timeEsercizio += 1
                lblTimerE.Text = toTime(timeEsercizio)
            Case "next"
                timeEsercizio += 1
                lblTimerE.Text = toTime(timeEsercizio)
            Case "last"
                timeEsercizio += 1
                lblTimerE.Text = toTime(timeEsercizio)
        End Select
        lblTimerA.Text = toTime(timeGlobal)
    End Sub

    Private Sub lstAllenamenti_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
    Handles lstAllenamenti.MouseUp
        Dim index As Integer
        index = Math.Floor(e.Y / lstAllenamenti.ItemHeight)
        'If lstAllenamenti.Items.Count > 0 Then
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If index > lstAllenamenti.Items.Count - 1 Then
                clearMnuSearch(True)
                ToolStripTextBox1.TextBox.Text = ""
                mnuScheda2.Show(lstAllenamenti, e.X, e.Y)
            Else
                lstAllenamenti.SelectedIndex = index
                SpostaSuToolStripMenuItem.Enabled = True
                SpostaGiuToolStripMenuItem.Enabled = True
                If index = 0 Then
                    SpostaSuToolStripMenuItem.Enabled = False
                ElseIf index = lstAllenamenti.Items.Count - 1 Then
                    SpostaGiuToolStripMenuItem.Enabled = False
                End If
                mnuScheda.Show(lstAllenamenti, lstAllenamenti.Width - 2, _
                   lstAllenamenti.ItemHeight * lstAllenamenti.SelectedIndex - 1)
                selectEsercizio(lstAllenamenti.SelectedIndex)
            End If
        ElseIf e.Button = Windows.Forms.MouseButtons.Left Then
            If lstAllenamenti.SelectedIndex > -1 Then selectEsercizio(lstAllenamenti.SelectedIndex)
        End If
        'End If
    End Sub

    'carica le preferenze 
    Sub loadPreferenze()
        defaultConfig() ' inizializza le preferenze con i valori di default
        readConfig("config.ini") ' leggi le preferene specificate nel file

        ' AGGIORNA PREFERENZE
        opzCapture(getConfig("cattura mouse")) ' aggiorna la preferenze di cattura mouse
    End Sub

    Private Sub CatturaMouseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles CatturaMouseToolStripMenuItem.Click
        If cmdAction.Enabled Then
            opzCapture(Not CatturaMouseToolStripMenuItem.Checked)
        End If
    End Sub

    Private Sub EsciToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles EsciToolStripMenuItem.Click
        End
    End Sub

    Private Sub cmdAction_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAction.MouseLeave
        If getConfig("cattura mouse") = "true" Then
            cmdAction.Focus()
            Cursor.Position = New Point(cmdAction.Location.X + Me.Location.X + cmdAction.Width / 2, _
                                        cmdAction.Location.Y + Me.Location.Y + cmdAction.Height / 2)
        End If
    End Sub

    Private Sub cmdAction_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmdAction.KeyUp
        If e.KeyCode = Keys.Escape And getConfig("cattura mouse") = "true" Then
            opzCapture(False)
        End If
    End Sub

    ' attiva o disattiva l'opzione di cattura del mouse
    Sub opzCapture(ByVal active As Boolean)
        If state = "editing" And active Then
            MsgBox("Non è possibile entrare nella modalità Cattura mouse durante la modifica")
            Exit Sub
        End If
        CatturaMouseToolStripMenuItem.Checked = active
        setConfig("cattura mouse", active.ToString.ToLower)
        If CatturaMouseToolStripMenuItem.Checked Then
            lblCapture.Text = "Cattura Mouse attivato - premere esc per disattivare"
            lblCapture.ForeColor = Color.Red
            Cursor.Position = New Point(cmdAction.Location.X + Me.Location.X + cmdAction.Width / 2, _
                                        cmdAction.Location.Y + Me.Location.Y + cmdAction.Height / 2)
            If cursorVisible Then
                Cursor.Hide()
                cursorVisible = False
            End If
        Else
            lblCapture.Text = "Cattura Mouse disattivato"
            lblCapture.ForeColor = Color.Black
            If Not cursorVisible Then
                Cursor.Show()
                cursorVisible = True
            End If
        End If
    End Sub

    Private Sub lblCapture_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles lblCapture.Click
        If cmdAction.Enabled Then
            opzCapture(True)
        End If
    End Sub

    Private Sub ToolStripTextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _
    Handles ToolStripTextBox1.KeyUp
        Dim tool As ToolStripMenuItem

        query("SELECT DISTINCT TOP " & getConfig("ricerca nome count") & " nome, id FROM esercizi WHERE nome LIKE '%" & _
              ToolStripTextBox1.TextBox.Text & "%'")

        searchMnuIds_count = 0

        If rs.RecordCount > 0 Then
            If rs.RecordCount <> mnuScheda2.Items.Count - 3 Then
                clearMnuSearch()
                ' visualizza la nuova ricerca nel menu
                While Not rs.EOF
                    tool = mnuScheda2.Items.Add(rs.Fields("nome").Value, Nothing, _
                                                AddressOf RisultatoMenu_Click)
                    tool.Name = rs.Fields("id").Value
                    searchMnuIds(searchMnuIds_count) = rs.Fields("id").Value
                    searchMnuIds_count += 1
                    rs.MoveNext()
                End While
            End If
        Else
            clearMnuSearch()
            tool = mnuScheda2.Items.Add("[Nessun risultato...]")
            tool.Enabled = False
            tool.TextAlign = ContentAlignment.MiddleCenter
        End If
    End Sub

    ' cancella gli elementi della ricerca
    Sub clearMnuSearch(Optional ByVal emptyMessage As Boolean = False)
        Dim tool As ToolStripMenuItem

        ' cancella la vecchia ricerca
        For i = 4 To mnuScheda2.Items.Count - 1
            mnuScheda2.Items.RemoveAt(4)
        Next

        If emptyMessage Then
            tool = mnuScheda2.Items.Add("[Nessun risultato...]")
            tool.Enabled = False
            tool.TextAlign = ContentAlignment.MiddleCenter
        End If
    End Sub

    Private Sub RisultatoMenu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim tool As ToolStripMenuItem = sender

        query("SELECT * FROM esercizi WHERE id=" & tool.Name)
        Dim def_carico As String
        If rs.Fields("def_carico").Value Is DBNull.Value Then
            def_carico = "null"
        Else
            def_carico = "'" & rs.Fields("def_carico").Value & "'"
        End If
        Dim def_serie As String = rs.Fields("def_serie").Value
        Dim def_spinte As String = rs.Fields("def_spinte").Value
        Dim def_pausa As String = rs.Fields("def_pausa").Value

        query("INSERT INTO qallenamento (allenamento.id,id_esercizio,giorno,carico,serie,spinte,pausa,ordine) " & _
              "VALUES(" & (currentAllenamento) & ", " & tool.Name & ", '" & (currentGiorno) & _
              "', " & def_carico & ", '" & def_serie & "', '" & def_spinte & "', '" & def_pausa & "', " & _
              lstAllenamenti.Items.Count & ") ")

        loadAllenamento(currentGiorno)
        lstAllenamenti.SelectedIndex = lstAllenamenti.Items.Count - 1
        changeEsercizio(lstAllenamenti.Items.Count - 1)
    End Sub

    Private Sub SpostaSuToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles SpostaSuToolStripMenuItem.Click
        Dim tmp As String
        Dim sel As Integer = lstAllenamenti.SelectedIndex
        If lstAllenamenti.SelectedIndex > 0 Then
            tmp = lstAllenamenti.Items.Item(sel)

            ' cambia ordine sel selezionato in -1 come temporaneo
            query("UPDATE qallenamento SET ordine=-1 WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=" & sel & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel) & "'")

            ' sposta nella posizione l'altro elemento
            query("UPDATE qallenamento SET ordine=" & sel & " WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=" & sel - 1 & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel - 1) & "'")

            ' poorta su l'elemento selezionato
            query("UPDATE qallenamento SET ordine=" & sel - 1 & " WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=-1" & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel) & "'")

            'aggiorna la lista
            loadAllenamento(currentGiorno)
            lstAllenamenti.SelectedIndex = sel - 1
            changeEsercizio(sel - 1)
        End If
    End Sub

    Private Sub SpostaGiuToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SpostaGiuToolStripMenuItem.Click
        Dim tmp As String
        Dim sel As Integer = lstAllenamenti.SelectedIndex
        If lstAllenamenti.SelectedIndex < lstAllenamenti.Items.Count - 1 Then
            tmp = lstAllenamenti.Items.Item(sel)

            ' cambia ordine sel selezionato in -1 come temporaneo
            query("UPDATE qallenamento SET ordine=-1 WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=" & sel & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel) & "'")

            ' sposta nella posizione l'altro elemento
            query("UPDATE qallenamento SET ordine=" & sel & " WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=" & sel + 1 & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel + 1) & "'")

            ' poorta su l'elemento selezionato
            query("UPDATE qallenamento SET ordine=" & sel + 1 & " WHERE allenamento.id=" & currentAllenamento & _
                  " AND  giorno='" & currentGiorno & "' AND ordine=-1" & _
                  " AND esercizi.nome='" & lstAllenamenti.Items.Item(sel) & "'")

            'aggiorna la lista
            loadAllenamento(currentGiorno)
            lstAllenamenti.SelectedIndex = sel + 1
            changeEsercizio(sel + 1)
        End If
    End Sub

    Private Sub lblLun_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles lblGiornoVen.MouseEnter, lblGiornoSab.MouseEnter, lblGiornoMer.MouseEnter, lblGiornoMar.MouseEnter, lblGiornoLun.MouseEnter, _
    lblGiornoGio.MouseEnter, lblGiornoDom.MouseEnter, lblCapture.MouseEnter
        Dim obj As Label = sender
        If obj.BackColor <> Color.AliceBlue Then
            obj.BackColor = Color.WhiteSmoke
        End If
    End Sub

    Private Sub lblLun_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles lblGiornoVen.MouseLeave, lblGiornoSab.MouseLeave, lblGiornoMer.MouseLeave, lblGiornoMar.MouseLeave, lblGiornoLun.MouseLeave, _
    lblGiornoGio.MouseLeave, lblGiornoDom.MouseLeave, lblCapture.MouseLeave
        Dim obj As Label = sender
        If obj.BackColor <> Color.AliceBlue Then
            obj.BackColor = Color.Gainsboro
        End If
    End Sub

    Private Sub lblLun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles lblGiornoVen.Click, lblGiornoSab.Click, lblGiornoMer.Click, lblGiornoMar.Click, lblGiornoLun.Click, lblGiornoGio.Click, lblGiornoDom.Click
        Dim obj As Label = sender
        If obj.Text.Substring(0, 3).ToLower <> currentGiorno Then
            resetDays()
            obj.BackColor = Color.AliceBlue
            loadAllenamento(obj.Text.Substring(0, 3).ToLower)
        End If
    End Sub

    Sub checkGiorno(ByRef l As Label)
        query("SELECT * FROM allenamento WHERE giorno='" + l.Text.Substring(0, 3).ToLower + "' AND id=" & currentAllenamento)
        If rs.RecordCount = 0 Then
            l.ForeColor = Color.Gray
        Else
            l.ForeColor = Color.Black
        End If
    End Sub

    Sub ingrigisciGiorniVuoti()
        checkGiorno(lblGiornoLun)
        checkGiorno(lblGiornoMar)
        checkGiorno(lblGiornoMer)
        checkGiorno(lblGiornoGio)
        checkGiorno(lblGiornoVen)
        checkGiorno(lblGiornoSab)
        checkGiorno(lblGiornoDom)
    End Sub

    Private Sub EliminaVoceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EliminaVoceToolStripMenuItem.Click
        query("DELETE FROM allenamento WHERE ordine=" & lstAllenamenti.SelectedIndex & _
              " AND id=" & currentAllenamento & " AND giorno='" & currentGiorno & "'")
        query("UPDATE allenamento SET ordine=ordine-1 WHERE ordine>" & lstAllenamenti.SelectedIndex & _
              " AND id=" & currentAllenamento & " AND giorno='" & currentGiorno & "'")
        loadAllenamento(currentGiorno)
    End Sub

    Private Sub ModificaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModificaToolStripMenuItem.Click
        setState("editing")
    End Sub

    Sub enableGiorno(ByVal b As Boolean)
        For Each o As Control In Me.Controls
            If o.Name.Contains("lblGiorno") Then
                o.Enabled = b
            End If
        Next
    End Sub

    Private Sub cmdAnnullaEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAnnullaEdit.Click
        gbEdit.Visible = False
        gbEs.Visible = True
        enableGiorno(True)
        lstAllenamenti.Enabled = True
        playSound("sound abort")
        setState("new")
    End Sub

    Sub loadGruppi()
        Dim i As Integer = 0

        query("SELECT DISTINCT gruppo FROM fasce")
        Dim gruppi(rs.RecordCount - 1) As String
        While Not rs.EOF
            gruppi(i) = rs.Fields(0).Value
            i += 1
            rs.MoveNext()
        End While

        For Each g As String In gruppi
            Dim m As New ToolStripMenuItem(g)
            CercaPerGruppoToolStripMenuItem.DropDownItems.Add(m)

            query("SELECT DISTINCT nome FROM fasce WHERE gruppo='" & g & "'")
            Dim fascia(rs.RecordCount - 1) As String
            i = 0
            While Not rs.EOF
                fascia(i) = rs.Fields(0).Value
                i += 1
                rs.MoveNext()
            End While

            For Each f As String In fascia
                Dim m2 As New ToolStripMenuItem(f)
                m.DropDownItems.Add(m2)
                query("SELECT * FROM qesercizi WHERE fasce.nome='" & f & "'")
                While Not rs.EOF
                    Dim m3 As ToolStripItem = m2.DropDownItems.Add(rs.Fields("esercizi.nome").Value)
                    m3.Name = rs.Fields("esercizi.id").Value
                    AddHandler m3.Click, AddressOf RisultatoMenu_Click
                    rs.MoveNext()
                End While
            Next

        Next
    End Sub

    Private Sub ExportToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportToolStripMenuItem.Click
        If dlgSave.ShowDialog() = Windows.Forms.DialogResult.OK Then
            If exportAllenamento(dlgSave.FileName) Then
                MsgBox("File esportato con successo.")
            Else
                MsgBox("Errore durante l'esportazione del file")
            End If
        End If
    End Sub
End Class
